import os 
import shutil
import os
OPENSLIDE_PATH = r'C:\openslide-win64-20231011\bin'
if hasattr(os, 'add_dll_directory'):
    # Windows
    with os.add_dll_directory(OPENSLIDE_PATH):
        import openslide
else:
    import openslide

import numpy as np 
import cv2
import xml.etree.ElementTree as ET
import tqdm
import threading
import copy
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor

path=r'/media/doge/doge/数据集/lin2024/4细胞浆+6/6 细胞浆+细胞核'
spath=r'./dataset_3_16'

classes_num = 8
window_size = 640

if not os.path.exists(spath):
    os.makedirs(spath)

# 创建 0 1 2 3 4文件夹 
for i in range (classes_num):
    if not os.path.exists(os.path.join(spath,str(i))):
        os.mkdir (os.path.join(spath,str(i))) 

pic_index = 0


def cut_and_save_image(region,image_name):
    
    
    print(image_name)
    region.save(image_name)

for i in tqdm.tqdm(os.listdir(path)):
    # print (i)
    if i.endswith('xml'):
        print (i)
        path1=os.path.join(path,i)
        
        ndpi_name = i.split('\\')[-1][:-4]
        train=i.split('\\')[-1][:-4]+'.ndpi'
        # print(i,img)
        # print(s1)
        img=os.path.join(path,train)


        # print(img,mask)
        # print(s2)
        slide = openslide.open_slide(img)
        width, height = slide.dimensions
#         # print(slide.dimensions)
#     # # # 定义每个小病理切片的大小
        tree = ET.parse(path1)
        root = tree.getroot()
        
        annotation1 =  list(root.iter('Annotation'))[0]


        # draw cells
        xyxy_list = []
        for region in annotation1.iter('Region'):

            list1=[]
            for vertex in region.iter('Vertex'):
                x = vertex.get('X')
                y = vertex.get('Y')
                list1.append([int(float(x)),int(float(y))])
            list_xyxy = [[list1[0][0],list1[0][1]],[list1[2][0],list1[2][1]],region.get('Text')]
            xyxy_list.append(copy.deepcopy(list_xyxy))

        
        process_pool = ProcessPoolExecutor(max_workers=12)


        tasks = []
        for xyxy in xyxy_list:
            label =   xyxy [2] 
            # if label !='0':
            start_x,start_y = xyxy[0][0] ,xyxy[0][1] 
            end_x,end_y = xyxy[1][0] ,xyxy[1][1]  
            for index_x in range (start_x,end_x,window_size):
                for index_y in range (start_y,end_y,window_size):
                    image_name=os.path.join(spath,label,f'{str(pic_index).zfill(4)}_{index_x}_{index_y}.png')
                    region = slide.read_region((index_x, index_y), 0, (window_size, window_size))
                    tasks.append(process_pool.submit(cut_and_save_image, region,image_name))
                    pic_index+=1
    
        for t in tasks:
            t.result()
        slide.close()

